﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Dynamic;
using Urs.Data.Domain.Users;
using Urs.Core.Infrastructure;
using Urs.Services.Users;

namespace Urs.Framework.Controllers
{
    public class BaseApiController : ControllerBase
    {
        private User _cachedUser;
        private User _cachedRegisterUser;
        public virtual User CurrentUser
        {
            get
            {
                if (_cachedUser != null)
                    return _cachedUser;

                User user = null;

                if (user == null || user.Deleted)
                {
                    var guid = string.Empty;
                    foreach (var item in HttpContext.Request.Headers)
                    {
                        if (item.Key == "Guid" || item.Key == "guid")
                        {
                            guid = item.Value;
                            break;
                        }
                    }
                    if (!String.IsNullOrEmpty(guid))
                    {
                        if (Guid.TryParse(guid, out Guid userGuid))
                        {
                            var userService = EngineContext.Current.Resolve<IUserService>();
                            var currentUser = userService.GetUserByGuid(userGuid);
                            if (currentUser != null)
                                user = currentUser;
                        }
                    }
                }

                if (!user.Deleted && user.Active)
                {
                    //cache the found user
                    _cachedUser = user;
                }

                return _cachedUser;
            }
            set
            {
                _cachedUser = value;
            }
        }

        public virtual User RegisterUser
        {
            get
            {
                if (_cachedRegisterUser != null)
                    return _cachedRegisterUser;

                User user = null;

                if (user == null || user.Deleted)
                {
                    var guid = RouteData.Values["guid"].ToString();
                    if (!String.IsNullOrEmpty(guid))
                    {
                        if (Guid.TryParse(guid, out Guid userGuid))
                        {
                            var userService = EngineContext.Current.Resolve<IUserService>();
                            var currentUser = userService.GetUserByGuid(userGuid);
                            if (currentUser != null)
                                user = currentUser;
                        }
                    }
                }

                if (!user.Deleted && user.Active)
                {
                    //cache the found user
                    _cachedRegisterUser = user;
                }

                return _cachedRegisterUser;
            }
            set
            {
                _cachedRegisterUser = value;
            }
        }
    }
}
